package com.abbas.smartCity.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.abbas.smartCity.App;
import com.abbas.smartCity.bean.UploadBean;
import com.abbas.smartCity.retroft.Api;
import com.abbas.smartCity.retroft.ICallback;
import com.abbas.smartCity.util.ActivityManager;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;

/**
 * Activity 封装
 */
public abstract class BaseActivity extends AppCompatActivity {


    //retrofit动态代理接口
    protected final Api api = App.getApi();
    protected static final Gson gson = App.gson;

    //图片选择请求码
    protected static final int PICK_IMAGE_REQUEST_CODE = 0x2134;
    //内存访问权限请求码
    protected static final int STORAGE_PERMISSION_REQUEST_CODE = 0x3421;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());

        //ActivityManager.getInstance().push(this);

        final ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayHomeAsUpEnabled(enableUp());
            supportActionBar.setTitle(setCustomTitle());
        }

        initView();
        initData();
        initEvent();

    }

    /**
     * 获取布局ID
     *
     * @return 布局ID
     */
    protected abstract int getLayoutId();

    /**
     * 子类重写此方法已决定是否启用页面左上角返回
     *
     * @return 默认true
     */
    protected boolean enableUp() {
        return true;
    }

    /**
     * 设置标题栏标题
     *
     * @return 标题
     */
    protected abstract String setCustomTitle();

    /**
     * 寻找控件、控件操作
     */
    protected abstract void initView();

    /**
     * 数据操作、网络操作
     */
    protected abstract void initData();

    /**
     * 监听设置、事件设置
     */
    protected abstract void initEvent();

    /**
     * 跳转至目标页面
     *
     * @param targetClazz 目标页面
     * @param <T>         目标页面Clazz
     */
    protected <T> void startActivity(Class<T> targetClazz) {
        startActivity(new Intent(this, targetClazz));
    }

    /**
     * 短暂的显示一个提示
     *
     * @param tip 提示信息
     */
    protected void showToast(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
    }

    /**
     * 右上角点击返回结束页面
     *
     * @param item 菜单
     * @return ???
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            this.finish();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 获取一个HashMap
     *
     * @return HashMap
     */
    protected static Map<String, Object> getMap() {
        return new HashMap<>();
    }

    /**
     * 获取一个RequestBody
     *
     * @param paramsMap 需要放入RequestBody的键值对Map数据
     * @return RequestBody
     */
    protected static RequestBody createRequestBody(Map<String, Object> paramsMap) {
        return RequestBody.create(MediaType.parse("application/json"), gson.toJson(paramsMap));
    }

    /**
     * 获取一个RequestBody
     *
     * @param paramsObj 需要放入RequestBody的数据对象
     * @return RequestBody
     */
    protected static RequestBody createRequestBody(Object paramsObj) {
        return RequestBody.create(MediaType.parse("application/json"), gson.toJson(paramsObj));
    }


    //**************************以下代码无需实现*********************//

    @Override
    protected void onDestroy() {
        ActivityManager.getInstance().remove(this);
        super.onDestroy();
    }


    //动态权限请求代码，竞赛不要求动态申请，因此我们一般在开屏页面即申请，测试老师不会拒绝
    //无需实现

    /**
     * 存储权限请求。用户授权将会回调
     * {@link BaseActivity#onStoragePermissionRequestSuccess()} //成功
     * {@link BaseActivity#onStoragePermissionRequestFailure()} //失败
     *
     * @return 是否已经授权
     */
    protected boolean requestStoragePermission() {
        if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            this.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_REQUEST_CODE);
            return false;
        }
    }

    //无须实现

    /**
     * 权限授权回调
     *
     * @param requestCode  请求码
     * @param permissions  请求权限清单
     * @param grantResults 同意授权的权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0) {
                onStoragePermissionRequestSuccess();
            } else {
                onStoragePermissionRequestFailure();
            }
        }
    }

    //无需实现

    /**
     * 从存储当中选择一张图片，优先判断是否含有权限
     */
    protected void startPickOneOfStorageImage() {
        if (requestStoragePermission()) {
            //为Intent设置Action和Type，以跳转到系统图库
            //比赛默认机型安卓8.0 无需判断当前机型版本
            final Intent intent = new Intent();
            intent.setAction(Intent.ACTION_PICK);
            intent.setType("image/*");
            //开始挑选
            startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE);
        }
    }

    //无需实现

    /**
     * 存储权限请求失败
     */
    protected void onStoragePermissionRequestFailure() {
    }

    //无需实现

    /**
     * 存储权限请求成功
     */
    protected void onStoragePermissionRequestSuccess() {
    }

    @SuppressLint("Range")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //优先判空 如果图库没有图片，返回应用时Intent将会为null造成闪退，一定要记得判空！！！
        if (requestCode == PICK_IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
            //--------------------固定写法----------------------
            final Uri uri = data.getData();
            //String[] _data = {MediaStore.Images.Media.DATA};
            //查询数据库
            final Cursor cursor = getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
            //记得判空，并将指针移动至第一位
            Objects.requireNonNull(cursor).moveToFirst();
            //获取图片真实路径
            final String path = cursor.getString(cursor.getColumnIndex("_data"));
            //解析图片
            final Bitmap storageImage = BitmapFactory.decodeFile(path);
            //关闭流
            Objects.requireNonNull(cursor).close();
            //--------------------结束-------------------------
            //回调
            onImagePickResult(path, storageImage);

            //上传图片
            //构造图片文件
            final File uploadImageFile = new File(path);
            //设置请求体数据格式，并将图片放入请求体
            final RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), uploadImageFile);
            //新建一个Part对象，将上传的文件传入并指定文件名
            final MultipartBody.Part multipartBody = MultipartBody.Part.createFormData("file", uploadImageFile.getName(), requestBody);
            api.postFile(
                    multipartBody
            ).enqueue(new ICallback<UploadBean>() {
                @Override
                public void onSuccess(Call<UploadBean> call, UploadBean data) {
                    //上传回调
                    onImagePickAndLoadUpResult(data, storageImage);
                }
            });

            //直接获取图片
//            try {
//                final Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
//                bitmap.recycle();
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }

        }
    }

    //无需实现

    /**
     * 选择图片结果
     *
     * @param path   图片绝对路径
     * @param bitmap 图片
     */
    protected void onImagePickResult(String path, Bitmap bitmap) {

    }

    //无需实现

    /**
     * 上传图片结果
     *
     * @param uploadBean 上传结果
     * @param bitmap     图片
     */
    protected void onImagePickAndLoadUpResult(UploadBean uploadBean, Bitmap bitmap) {

    }


}
